package com.dbh.alg.algorithm.important;


import com.dbh.alg.algorithm.hot100.ListNode;

/**
 * 给你两个 非空 的链表，表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储 一位 数字。
 */
public class Leetcode2_两数相加 {


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode s = new ListNode(-1);
        int carry = 0;
        while(l1 != null || l2 != null || carry > 0) {
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            int sum = x + y + carry;
            int yu = sum % 10;
            carry = sum / 10;
            ListNode node = new ListNode(yu);
            node.next = s.next;
            s.next = node;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        return  reverse(s.next);
    }

    public ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

}
